Step 6: Debug in Webstorm
Webstorm is a great IDE for web development, a viable alternative to VSCode. I found debugging, and refactoring are supported much better in Webstorm. Let’s open this project in Webstorm. Moreover, let's install the Vitest Runner plugin for Webstorm. Notice once the plugin is installed, you get a widget next to each test to run it.
I added a breakpoint to line 85 of tests/data/BookmarkDAO.test.js
file. To that aim, you can click on the area next to the line number. Now, click on the Vitest icon and select the “Debug” option.
You should see the debugger in action. You can step through your code line by line and step in and out of functions. If you have taken Data Structures with me, you should be familiar with the debugger. If not, this short read might help.
If you follow the code, you will realize the bug is in the delete
operation of BookmarkDAO
class, where we call splice
on this.bookmarks
when index
is -1
delete(id) {
const index = this.bookmarks.findIndex((bookmark) => bookmark.id === id);
const bookmark = this.bookmarks[index];
this.bookmarks.splice(index, 1);
return bookmark;
}
To squash the bug, guard against this scenario:
delete(id) {
const index = this.bookmarks.findIndex((bookmark) => bookmark.id === id);
if (index !== -1) {
const bookmark = this.bookmarks[index];
this.bookmarks.splice(index, 1);
return bookmark;
}
return undefined;
}
Let’s run the tests again! Does the test still fail?! Well, debug it!
You will probably realize the debugger is not much of the help here! You should follow the data flow of the program and form a hypothesis as to where the bug could be based on your understanding of how the app and the tests work.
A careful investigation will reveal that the issue resides in multiple tests modifying a shared array of bookmarks. In the tests, notice every instance that you have the following code:
bookmarkDao.bookmarks = bookmarks;
You should replace the code above with the one bellow (think why):
bookmarkDao.bookmarks = bookmarks.map(b => b);
Run the tests again!
Save and commit the changes.